import os
import json
import platform
import subprocess

import ffmpy3
from .spider import spider


def get_video_list(opt):
    vidlist = None
    try:
        jsonf = open('Videos.json', 'r', encoding='utf-8')
    except FileNotFoundError:
        print('视频列表文件不存在！')
        spider(opt)
    else:
        vidlist = json.load(jsonf)
    return vidlist


def vid_trans_encode(vid):
    if platform.system() == 'Windows':
        ffmpy3.FFmpeg(
            executable='ffmpeg.exe',
            inputs={'Videos/%s.flv' % (vid['id']): None},
            outputs={'Videos/%s.mp4' % (vid['id']): '-c copy'}
        ).run(stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    elif platform.system() == 'Linux':
        ffmpy3.FFmpeg(
            executable='ffmpeg',
            inputs={'./Videos/%s.flv' % (vid['id']): None},
            outputs={'./Videos/%s.mp4' % (vid['id']): '-c:v libx264'}
        ).run(stdout=subprocess.PIPE, stderr=subprocess.STDOUT)


def down(opt):
    baseurl = opt['DwBaseSite']
    vlist = get_video_list(opt)
    for i in vlist:
        if i['type'] in opt['DwVideoType']:
            url = baseurl + i['bv']
            if os.path.exists('./Videos/%s.flv' % (i['id'])) or os.path.exists('./Videos/%s.mp4' % (i['id'])):
                print('文件已存在！')
                continue
            else:
                os.system('you-get --format=flv -O %s -o ./Videos %s' % (str(i['id']), url))
                vid_trans_encode(i)
                if platform.system() == 'Windows':
                    os.system(r'del Videos\*.xml')
                    os.system(r'del Videos\*.flv')
                elif platform.system() == 'Linux':
                    os.system('rm Videos/*.xml')
                    os.system('rm Videos/*.flv')
